package 力扣91;

import java.util.Stack;

/**
 * @ClassName : Day4_394_字符串解码_lc题解_lc题解
 * @Author : 骆发茂
 * @Date: 2021/12/15 22:22
 * @Description : * @Description : https://leetcode-cn.com/problems/decode-string/
 * https://leetcode-cn.com/problems/decode-string/solution/jian-dan-de-yi-dong-de-javadan-zhan-mo-n-9qfc/
 */
public class Day4_394_字符串解码_lc题解_没看懂1 {
    class Solution {
        public String decodeString(String s) {
            String result = "";     //存放答案

            Stack<String> sta = new Stack<>();      //只使用一个栈

            for (int i = 0; i < s.length(); i++) {
                String current = s.charAt(i) + "";

                //当前元素不为右括号时压入栈
                if (!current.equals("]")) {
                    sta.push(current);
                }
                //当前元素为右括号时，开始处理栈中元素
                else {
                    //以栈中第一个左括号为界限，取出所有字符
                    String cur = "";
                    while (!sta.peek().equals("[")) {
                        cur = sta.pop() + cur;
                    }
                    //弹出左括号
                    sta.pop();
                    //取出系数
                    String p = "";
                    while (!sta.isEmpty() &&
                            sta.peek().compareTo("0") >= 0 && sta.peek().compareTo("9") <= 0) {
                        p = sta.pop() + p;
                    }
                    int flag = Integer.parseInt(p);
                    //累加
                    String l = cur;
                    for (int j = 1; j < flag; j++) {
                //    cur += l;   //开始这里我使用了 cur += cur 来更新，显然这是错误的
                    }
                    //处理结束，将元素压回栈中
                    sta.push(cur);
                }
            }
            //拼接元素
            while (!sta.isEmpty()) {
                result = sta.pop() + result;
            }
            return result;
        }
    }

}